<template>
	<view class="container">
		<!-- 数据库状态组件 -->
		<password-storage ref="storage" @storage-ready="onStorageReady" @storage-error="onStorageError" />
		
		<view class="header">
			<text class="title">我的密码列表</text>
		</view>
		
		<!-- 搜索框 -->
		<view class="search-container">
			<view class="search-box">
				<text class="search-icon">🔍</text>
				<input 
					class="search-input" 
					v-model="searchKeyword" 
					placeholder="搜索标题、用户名或备注..."
					@input="onSearchInput"
				/>
				<text v-if="searchKeyword" class="clear-icon" @click="clearSearch">×</text>
			</view>
		</view>
		
		<!-- 加载状态 -->
		<view v-if="loading" class="loading-tip">
			<text class="loading-text">正在加载数据...</text>
		</view>
		
		<!-- 密码列表 -->
		<view v-else-if="displayPasswords.length === 0" class="empty-tip">
			<text class="empty-icon">{{ searchKeyword ? '🔑' : '🔑' }}</text>
			<text class="empty-text">{{ searchKeyword ? '没有找到相关密码' : '暂无密码，点击右下角新增' }}</text>
		</view>
		<view v-else class="password-list">
			<view 
				class="password-item" 
				v-for="(item, idx) in displayPasswords" 
				:key="item.id"
				@click="showActionSheet(idx)"
				@longpress="showActionSheet(idx)"
			>
				<view class="item-left">
					<view class="item-icon">🔑</view>
					<view class="item-info">
						<text class="item-title">{{item.title}}</text>
						<text class="item-username">{{item.username}}</text>
						<text v-if="item.remark" class="item-remark">{{item.remark}}</text>
					</view>
				</view>
				<view class="item-right">
					<view class="copy-icon" @click.stop="copyPassword(item.password)">
						<text class="icon">🔑</text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 搜索结果统计 -->
		<view v-if="searchKeyword && displayPasswords.length > 0" class="search-stats">
			<text class="stats-text">找到 {{ displayPasswords.length }} 个结果</text>
		</view>
		
		<!-- 可拖动悬浮新增按钮 -->
		<view 
			class="fab-button" 
			:class="{ 'dragging': isDragging }"
			:style="{ 
				left: fabPosition.x + 'px', 
				top: fabPosition.y + 'px',
				transform: isDragging ? 'scale(1.1)' : 'scale(1)'
			}"
			@touchstart="onTouchStart"
			@touchmove="onTouchMove"
			@touchend="onTouchEnd"
		>
			<text class="fab-icon">+</text>
		</view>
		
		<!-- 新增/编辑弹窗 -->
		<view v-if="showAddModal" class="modal-overlay" @click="closeModal">
			<view class="modal" :class="{ 'keyboard-open': keyboardHeight > 0 }" @click.stop>
				<view class="modal-header">
					<text class="modal-title">{{editIndex === -1 ? '新增密码' : '编辑密码'}}</text>
					<text class="modal-close" @click="closeModal">×</text>
				</view>
				
				<scroll-view 
					class="modal-body" 
					scroll-y="true"
					:scroll-top="scrollTop"
					:scroll-with-animation="true"
				>
					<view class="form-item">
						<text class="form-label">标题/网站</text>
						<input 
							v-model="form.title" 
							placeholder="请输入标题或网站名称" 
							class="form-input"
							:focus="currentFocus === 'title'"
							@focus="onInputFocus('title')"
							@blur="onInputBlur"
						/>
					</view>
					<view class="form-item">
						<text class="form-label">用户名</text>
						<input 
							v-model="form.username" 
							placeholder="请输入用户名" 
							class="form-input"
							:focus="currentFocus === 'username'"
							@focus="onInputFocus('username')"
							@blur="onInputBlur"
						/>
					</view>
					<view class="form-item">
						<text class="form-label">密码</text>
						<view class="password-input-wrapper">
							<input 
								v-model="form.password" 
								:type="showPassword ? 'text' : 'password'"
								placeholder="请输入密码" 
								class="form-input password-input"
								:focus="currentFocus === 'password'"
								@focus="onInputFocus('password')"
								@blur="onInputBlur"
							/>
							<view class="password-toggle" @click="togglePasswordVisibility">
								<text class="toggle-icon">{{ showPassword ? '👁️' : '🔒' }}</text>
							</view>
						</view>
					</view>
					<view class="form-item">
						<text class="form-label">备注</text>
						<textarea 
							v-model="form.remark" 
							placeholder="请输入备注（可选）" 
							class="form-textarea"
							:focus="currentFocus === 'remark'"
							@focus="onInputFocus('remark')"
							@blur="onInputBlur"
						/>
					</view>
					
					<!-- 底部占位，确保最后一个输入框不被遮挡 -->
					<view class="bottom-spacer" :style="{ height: keyboardHeight + 'px' }"></view>
				</scroll-view>
				
				<view class="modal-footer">
					<button class="btn-cancel" @click="closeModal">取消</button>
					<button class="btn-save" @click="savePassword">保存</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import PasswordStorage from '@/components/PasswordStorage.vue'

	export default {
	components: {
		PasswordStorage
	},
		data() {
			return {
			passwords: [],
			displayPasswords: [], // 显示的密码列表（搜索结果）
			searchKeyword: '', // 搜索关键词
			loading: true,
			showAddModal: false,
			form: { title: '', username: '', password: '', remark: '' },
			editIndex: -1,
			showPassword: false,
			// 键盘相关
			keyboardHeight: 0,
			currentFocus: '',
			scrollTop: 0,
			// 悬浮按钮位置
			fabPosition: {
				x: 0,
				y: 0
			},
			// 拖动相关状态
			isDragging: false,
			startPosition: {
				x: 0,
				y: 0
			},
			// 屏幕尺寸
			screenWidth: 0,
			screenHeight: 0,
			// 拖动阈值
			dragThreshold: 10,
			// 是否已经触发拖动
			hasDragged: false
		}
	},
	mounted() {
		// 获取屏幕尺寸
		const systemInfo = uni.getSystemInfoSync()
		this.screenWidth = systemInfo.windowWidth
		this.screenHeight = systemInfo.windowHeight
		
		// 设置初始位置（右下角）
		this.fabPosition.x = this.screenWidth - 80
		this.fabPosition.y = this.screenHeight - 120
		
		// 监听键盘事件
		this.initKeyboardListener()
	},
	beforeDestroy() {
		// 移除键盘监听
		this.removeKeyboardListener()
	},
	methods: {
		// 搜索输入处理
		onSearchInput() {
			this.filterPasswords()
		},
		
		// 清空搜索
		clearSearch() {
			this.searchKeyword = ''
			this.filterPasswords()
		},
		
		// 过滤密码列表
		filterPasswords() {
			if (!this.searchKeyword.trim()) {
				this.displayPasswords = [...this.passwords]
				return
			}
			
			const keyword = this.searchKeyword.toLowerCase().trim()
			this.displayPasswords = this.passwords.filter(item => {
				// 搜索标题、用户名、备注（不区分大小写）
				return (
					item.title.toLowerCase().includes(keyword) ||
					item.username.toLowerCase().includes(keyword) ||
					(item.remark && item.remark.toLowerCase().includes(keyword))
				)
			})
		},
		
		// 初始化键盘监听
		initKeyboardListener() {
			// 监听键盘弹出
			uni.onKeyboardHeightChange((res) => {
				this.keyboardHeight = res.height
				console.log('键盘高度变化:', res.height)
				
				// 如果有输入框获得焦点，滚动到对应位置
				if (this.currentFocus && res.height > 0) {
					this.scrollToFocusedInput()
				}
			})
		},
		
		// 移除键盘监听
		removeKeyboardListener() {
			// uni-app 会自动清理监听器，这里可以添加其他清理逻辑
		},
		
		// 滚动到获得焦点的输入框
		scrollToFocusedInput() {
			const focusMap = {
				'title': 0,
				'username': 120,
				'password': 240,
				'remark': 360
			}
			
			const scrollPosition = focusMap[this.currentFocus] || 0
			this.scrollTop = scrollPosition
		},
		
		// 输入框获得焦点
		onInputFocus(field) {
			this.currentFocus = field
			console.log('输入框获得焦点:', field)
			
			// 延迟滚动，确保键盘完全弹出
			setTimeout(() => {
				this.scrollToFocusedInput()
			}, 300)
		},
		
		// 输入框失去焦点
		onInputBlur() {
			this.currentFocus = ''
			console.log('输入框失去焦点')
		},
		
		// 切换密码显示
		togglePasswordVisibility() {
			this.showPassword = !this.showPassword
		},
		
		// 存储系统就绪回调
		onStorageReady() {
			console.log('存储系统就绪，开始加载数据')
			this.loadPasswords()
		},
		
		// 存储系统错误回调
		onStorageError(error) {
			console.error('存储系统错误:', error)
			this.loading = false
			uni.showToast({ 
				title: '存储系统初始化失败', 
				icon: 'none',
				duration: 2000
			})
		},
		
		// 加载密码列表
		async loadPasswords() {
			try {
				console.log('开始加载密码数据...')
				const passwords = await this.$refs.storage.getAllPasswords()
				console.log('加载到的密码数据:', passwords)
				this.passwords = passwords || []
				this.displayPasswords = [...this.passwords] // 初始化显示列表
				this.loading = false
			} catch (error) {
				console.error('加载密码失败:', error)
				this.loading = false
				uni.showToast({ 
					title: '加载失败: ' + error.message, 
					icon: 'none',
					duration: 2000
				})
			}
		},
		
		// 触摸开始
		onTouchStart(e) {
			this.isDragging = false
			this.hasDragged = false
			this.startPosition = {
				x: e.touches[0].clientX,
				y: e.touches[0].clientY
			}
		},
		
		// 触摸移动
		onTouchMove(e) {
			const currentX = e.touches[0].clientX
			const currentY = e.touches[0].clientY
			
			// 计算移动距离
			const deltaX = currentX - this.startPosition.x
			const deltaY = currentY - this.startPosition.y
			const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY)
			
			// 如果移动距离超过阈值，开始拖动
			if (distance > this.dragThreshold) {
				this.isDragging = true
				this.hasDragged = true
				
				// 计算新位置
				const newX = this.fabPosition.x + deltaX
				const newY = this.fabPosition.y + deltaY
				
				// 限制按钮不超出屏幕边界
				const maxX = this.screenWidth - 80
				const maxY = this.screenHeight - 80
				
				this.fabPosition.x = Math.max(20, Math.min(newX, maxX))
				this.fabPosition.y = Math.max(20, Math.min(newY, maxY))
				
				// 更新起始位置，实现连续拖动
				this.startPosition = {
					x: currentX,
					y: currentY
				}
			}
		},
		
		// 触摸结束
		onTouchEnd(e) {
			// 如果只是点击（没有拖动），则触发新增功能
			if (!this.hasDragged) {
				this.showAddForm()
			}
			
			// 延迟重置拖动状态，让动画效果完成
			setTimeout(() => {
				this.isDragging = false
				this.hasDragged = false
			}, 100)
		},
		
		// 显示操作菜单
		showActionSheet(index) {
			const item = this.displayPasswords[index] // 使用显示列表中的项目
			uni.showActionSheet({
				itemList: ['复制用户名', '复制密码', '复制用户名和密码', '编辑', '删除'],
				success: (res) => {
					switch(res.tapIndex) {
						case 0: // 复制用户名
							this.copyToClipboard(item.username, '用户名')
							break
						case 1: // 复制密码
							this.copyToClipboard(item.password, '密码')
							break
						case 2: // 复制用户名和密码
							this.copyToClipboard(`${item.username}\n${item.password}`, '用户名和密码')
							break
						case 3: // 编辑
							this.showEditForm(item) // 传递完整的项目对象
							break
						case 4: // 删除
							this.deletePassword(item) // 传递完整的项目对象
							break
					}
				}
			})
		},
		
		// 复制到剪贴板
		copyToClipboard(text, type) {
			uni.setClipboardData({
				data: text,
				success: () => {
					uni.showToast({ 
						title: `已复制${type}`, 
						icon: 'success',
						duration: 1500
					})
				}
			})
		},
		
		// 快速复制密码
		copyPassword(password) {
			this.copyToClipboard(password, '密码')
		},
		
		// 显示新增表单
		showAddForm() {
			// 清理表单数据
			this.form = { title: '', username: '', password: '', remark: '' }
			this.editIndex = -1
			this.showPassword = false
			this.currentFocus = ''
			this.scrollTop = 0
			this.showAddModal = true
		},
		
		// 显示编辑表单
		showEditForm(item) {
			// 找到在原始列表中的索引
			const originalIndex = this.passwords.findIndex(p => p.id === item.id)
			this.editIndex = originalIndex
			this.form = { ...item }
			this.showPassword = false
			this.currentFocus = ''
			this.scrollTop = 0
			this.showAddModal = true
		},
		
		// 删除密码
		async deletePassword(item) {
			uni.showModal({
				title: '确认删除',
				content: '确定要删除这个密码吗？',
				success: async (res) => {
					if (res.confirm) {
						try {
							await this.$refs.storage.deletePassword(item.id)
							// 从原始列表和显示列表中删除
							const originalIndex = this.passwords.findIndex(p => p.id === item.id)
							if (originalIndex !== -1) {
								this.passwords.splice(originalIndex, 1)
							}
							this.filterPasswords() // 重新过滤显示列表
							uni.showToast({ title: '已删除', icon: 'success' })
						} catch (error) {
							console.error('删除失败:', error)
							uni.showToast({ title: '删除失败', icon: 'none' })
						}
					}
				}
			})
		},
		
		// 保存密码
		async savePassword() {
			if (!this.form.title || !this.form.username || !this.form.password) {
				uni.showToast({ title: '请填写完整信息', icon: 'none' })
				return
			}
			
			try {
				if (this.editIndex === -1) {
					// 新增
					const newId = await this.$refs.storage.savePassword(this.form)
					const newPassword = {
						id: newId,
						...this.form,
						created_at: new Date().toISOString(),
						updated_at: new Date().toISOString()
					}
					this.passwords.unshift(newPassword)
				} else {
					// 编辑
					const item = this.passwords[this.editIndex]
					await this.$refs.storage.updatePassword(item.id, this.form)
					this.passwords.splice(this.editIndex, 1, {
						...item,
						...this.form,
						updated_at: new Date().toISOString()
					})
				}
				
				// 重新过滤显示列表
				this.filterPasswords()
				
				this.closeModal()
				uni.showToast({ title: '保存成功', icon: 'success' })
			} catch (error) {
				console.error('保存失败:', error)
				uni.showToast({ title: '保存失败', icon: 'none' })
			}
		},
		
		// 关闭弹窗
		closeModal() {
			this.showAddModal = false
			// 清理表单数据
			this.form = { title: '', username: '', password: '', remark: '' }
			this.editIndex = -1
			this.showPassword = false
			this.currentFocus = ''
			this.scrollTop = 0
			this.keyboardHeight = 0
		}
		}
	}
</script>

<style>
.container {
	padding: 30rpx;
	min-height: 100vh;
	background: #f5f5f5;
}

.header {
	margin-bottom: 30rpx;
}

.title {
	font-size: 40rpx;
	font-weight: bold;
	color: #333;
}

/* 搜索框样式 */
.search-container {
	margin-bottom: 30rpx;
}

.search-box {
	position: relative;
	display: flex;
	align-items: center;
	background: #fff;
	border-radius: 12rpx;
	padding: 0 20rpx;
	box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.05);
}

.search-icon {
	font-size: 32rpx;
	margin-right: 15rpx;
	color: #999;
}

.search-input {
	flex: 1;
	height: 80rpx;
	font-size: 28rpx;
	color: #333;
	background: transparent;
}

.clear-icon {
	font-size: 36rpx;
	color: #999;
	padding: 10rpx;
	margin-left: 10rpx;
}

/* 搜索结果统计 */
.search-stats {
	text-align: center;
	margin-bottom: 20rpx;
}

.stats-text {
	font-size: 24rpx;
	color: #666;
	background: #fff;
	padding: 10rpx 20rpx;
	border-radius: 20rpx;
	display: inline-block;
}

.loading-tip {
	display: flex;
	justify-content: center;
	align-items: center;
	margin-top: 200rpx;
}

.loading-text {
	font-size: 28rpx;
	color: #666;
}

.empty-tip {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	margin-top: 200rpx;
}

.empty-icon {
	font-size: 120rpx;
	margin-bottom: 20rpx;
}

.empty-text {
	font-size: 28rpx;
	color: #999;
}

.password-list {
	margin-bottom: 120rpx;
}

.password-item {
	background: #fff;
	border-radius: 16rpx;
	padding: 24rpx;
	margin-bottom: 20rpx;
	display: flex;
	justify-content: space-between;
	align-items: center;
	box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.05);
}

.item-left {
	display: flex;
	align-items: center;
	flex: 1;
}

.item-icon {
	font-size: 40rpx;
	margin-right: 20rpx;
}

.item-info {
	flex: 1;
}

.item-title {
	font-size: 32rpx;
	font-weight: 500;
	color: #333;
	display: block;
}

.item-username {
	font-size: 26rpx;
	color: #666;
	margin-top: 8rpx;
	display: block;
}

.item-remark {
	font-size: 24rpx;
	color: #999;
	margin-top: 6rpx;
	display: block;
}

.item-right {
	display: flex;
	align-items: center;
}

.copy-icon {
	padding: 10rpx;
}

.icon {
	font-size: 32rpx;
}

/* 可拖动悬浮按钮 */
.fab-button {
	position: fixed;
	width: 100rpx;
	height: 100rpx;
	background: linear-gradient(135deg, #007aff, #0056cc);
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	box-shadow: 0 4rpx 16rpx rgba(0,122,255,0.3);
	z-index: 999;
	transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
	user-select: none;
	-webkit-user-select: none;
}

.fab-button.dragging {
	box-shadow: 0 8rpx 24rpx rgba(0,122,255,0.4);
}

.fab-icon {
	color: #fff;
	font-size: 48rpx;
	font-weight: bold;
	user-select: none;
	-webkit-user-select: none;
}

/* 弹窗样式 */
.modal-overlay {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: rgba(0, 0, 0, 0.5);
	display: flex;
	align-items: center;
	justify-content: center;
	z-index: 1000;
	padding: 40rpx;
}

.modal {
	background: #fff;
	border-radius: 20rpx;
	width: 100%;
	max-width: 600rpx;
	max-height: 80vh;
	display: flex;
	flex-direction: column;
	transition: all 0.3s ease;
	overflow: hidden;
}

.modal.keyboard-open {
	max-height: 90vh;
}

.modal-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 30rpx 30rpx 20rpx;
	border-bottom: 1rpx solid #eee;
	flex-shrink: 0;
}

.modal-title {
	font-size: 36rpx;
	font-weight: bold;
	color: #333;
}

.modal-close {
	font-size: 40rpx;
	color: #999;
	padding: 10rpx;
}

.modal-body {
	flex: 1;
	padding: 30rpx;
	overflow-y: auto;
	box-sizing: border-box;
}

.form-item {
	margin-bottom: 30rpx;
	width: 100%;
	box-sizing: border-box;
}

.form-label {
	font-size: 28rpx;
	color: #333;
	margin-bottom: 12rpx;
	display: block;
	font-weight: 500;
}

.form-input {
	width: 100%;
	height: 80rpx;
	border: 1rpx solid #ddd;
	border-radius: 8rpx;
	padding: 0 20rpx;
	font-size: 28rpx;
	box-sizing: border-box;
	background: #fff;
	max-width: 100%;
}

.form-input:focus {
	border-color: #007aff;
	box-shadow: 0 0 0 2rpx rgba(0,122,255,0.1);
}

.password-input-wrapper {
	position: relative;
	display: flex;
	align-items: center;
	width: 100%;
	box-sizing: border-box;
}

.password-input {
	padding-right: 80rpx;
	width: 100%;
	box-sizing: border-box;
}

.password-toggle {
	position: absolute;
	right: 20rpx;
	top: 50%;
	transform: translateY(-50%);
	padding: 10rpx;
	z-index: 10;
	pointer-events: auto;
}

.toggle-icon {
	font-size: 32rpx;
}

.form-textarea {
	width: 100%;
	height: 120rpx;
	border: 1rpx solid #ddd;
	border-radius: 8rpx;
	padding: 20rpx;
	font-size: 28rpx;
	box-sizing: border-box;
	background: #fff;
	resize: none;
	max-width: 100%;
}

.form-textarea:focus {
	border-color: #007aff;
	box-shadow: 0 0 0 2rpx rgba(0,122,255,0.1);
}

.bottom-spacer {
	width: 100%;
	box-sizing: border-box;
}

.modal-footer {
	display: flex;
	padding: 20rpx 30rpx 30rpx;
	border-top: 1rpx solid #eee;
	flex-shrink: 0;
	box-sizing: border-box;
}

.btn-cancel, .btn-save {
	flex: 1;
	height: 80rpx;
	border-radius: 8rpx;
	font-size: 28rpx;
	margin: 0 10rpx;
	border: none;
	box-sizing: border-box;
}

.btn-cancel {
	background: #f5f5f5;
	color: #666;
}

.btn-save {
	background: #007aff;
	color: #fff;
}

.btn-save:active {
	background: #0056cc;
}

/* 针对小屏幕的优化 */
@media screen and (max-width: 750rpx) {
	.modal {
		max-width: 90vw;
		margin: 0 20rpx;
	}
	
	.modal-body {
		padding: 20rpx;
	}
	
	.form-input, .form-textarea {
		font-size: 32rpx;
	}
}
</style>
